﻿
using IdentityModel;
using IdentityModel.Client;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Models.Common;
using Models.Identity;
using Models.JsonResultModel;
using Models.WebClient;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Net.Http.Headers;
using System.Security.Principal;
using UtilsORM;
using UtilsORM.MySqlData;
using ServiceWeb.APIRequest;
using ServiceWeb.DBGateway;
using UtilsBase;
using FileServer.Controllers.API.Common;
using UtilsCache;
using ServiceWeb.WebAdmin;
using UtilsORM.FileServerData;
using FileServer.Common;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
using Microsoft.CodeAnalysis;
using System.IO.Compression;
using SharpCifs.Netbios;
using static NPOI.SS.Formula.PTG.AttrPtg;


namespace FileServer.Controllers.API
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    // [BasicAuthentication]
    public class FileController : BaseMagerController
    {
        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="name"></param>
        /// <param name="parentGuid"></param>
        /// <param name="spaceType"></param>
        /// <returns></returns>
        public RespResultData getFileList([FromForm] string name, [FromForm] string parentGuid, [FromForm] int spaceType)
        {
            List<f_file> files = new ServiceFile().getList(base.LoginUserInfo.user_id, name, parentGuid, spaceType);
            return RespResult.Sucess(files);
        }

        /// <summary>
        /// 获取父级id
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public RespResultData getParnetGuid([FromForm] string guid)
        {
            f_file file = new ServiceFile().getFileModel(guid);
            if (file == null || file.guid == file.parent_guid)
            {
                return RespResult.Sucess(null);
            }
            else
            {
                return RespResult.Sucess(file.parent_guid);
            }
        }

        /// <summary>
        /// 获取文件信息
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public RespResultData getGuid([FromForm] string guid)
        {
            f_file file = new ServiceFile().getFileModel(guid);
            return RespResult.Sucess(file);
        }


        private readonly string _personfileServerDir = UtilAppsettingCache.getSetting("base:personFileServerDir");
        private readonly string _publicfileServerDir = UtilAppsettingCache.getSetting("base:publicFileServerDir");
        public readonly string _CurrentDirectory = "";// System.Environment.CurrentDirectory + "/";

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="parentGuid"></param>
        /// <param name="spaceType"></param>
        /// <returns></returns>
        public async Task<RespResultData> uploadFile(IFormFile file, string parentGuid, int spaceType)
        {
            if (file == null || file.Length == 0)
            {
                return RespResult.Faild("未选择文件");
            }

            string _fileServerDir = "";
            if (spaceType == 0)
            {
                //个人空间
                _fileServerDir = _personfileServerDir + "/" + base.LoginUserInfo.user_guid;
            }
            else
            {//公共空间
                _fileServerDir = _publicfileServerDir;
            }
            // 确保文件夹存在
            if (!Directory.Exists(_CurrentDirectory + _fileServerDir))
            {
                Directory.CreateDirectory(_CurrentDirectory + _fileServerDir);
            }

            string newFileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
            // var  filePath = Path.Combine(_fileServerDir, newFileName);


            //查询父目录
            string dirParentPath = new ServiceFile().getDirByGuid(parentGuid);

            // 完成目录 
            var filePath = Path.Combine(_fileServerDir + "/" + dirParentPath, file.FileName);

            // 保存文件
            using (var stream = new FileStream(_CurrentDirectory + filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            f_file fileInfo = new f_file();

            if (string.IsNullOrEmpty(parentGuid))
            {
                fileInfo.guid = Guid.NewGuid().ToString();
                fileInfo.parent_guid = fileInfo.guid;
            }
            else
            {
                fileInfo.guid = Guid.NewGuid().ToString();
                fileInfo.parent_guid = parentGuid;
            }


            fileInfo.name = file.FileName;
            fileInfo.system_name = newFileName;
            fileInfo.path = dirParentPath;
            fileInfo.size = file.Length;
            fileInfo.extension = Path.GetExtension(file.FileName);
            fileInfo.create_time = DateTime.Now;
            fileInfo.update_time = DateTime.Now;
            fileInfo.parent_id = 0;
            fileInfo.type = "file";
            fileInfo.user_id = base.LoginUserInfo.user_id;
            fileInfo.user_guid = base.LoginUserInfo.user_guid;
            fileInfo.from = "api";
            fileInfo.status = 0;
            fileInfo.space_type = spaceType;
            fileInfo.code = new UtilsOrderID().getCode1();
            new ServiceFile().add(fileInfo, parentGuid);
            return RespResult.Sucess("文件上传成功");
        }
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="parentGuid"></param>
        /// <param name="name"></param>
        /// <param name="spaceType"></param>
        /// <returns></returns>
        public RespResultData createDir([FromForm] string parentGuid, [FromForm] string name, [FromForm] int spaceType)
        {
            name = name.Trim();
            if (name == null || name.Length == 0)
            {
                return RespResult.Faild("填写文件夹名称");
            }

            string _fileServerDir = "";
            if (spaceType == 0)
            {
                //个人空间
                _fileServerDir = _personfileServerDir + "/" + base.LoginUserInfo.user_guid;
            }
            else
            {  //公共空间
                _fileServerDir = _publicfileServerDir;
            }
            // 确保文件夹存在
            if (!Directory.Exists(_CurrentDirectory + _fileServerDir))
            {
                Directory.CreateDirectory(_CurrentDirectory + _fileServerDir);
            }

            //查询父目录
            string dirParentPath = new ServiceFile().getDirByGuid(parentGuid);
            if (String.IsNullOrEmpty(dirParentPath))
            {
                return RespResult.Faild("父目录不存在");
            }
            string dirPath = _fileServerDir + "/" + dirParentPath + "/" + name;

            dirPath = dirPath.Replace("//", "/");
            dirPath = dirPath.Replace("//", "/");
            // 确保文件夹存在
            if (!Directory.Exists(_CurrentDirectory + dirPath))
            {
                Directory.CreateDirectory(_CurrentDirectory + dirPath);
            }


            f_file fileInfo = new f_file();

            if (string.IsNullOrEmpty(parentGuid))
            {
                fileInfo.guid = Guid.NewGuid().ToString();
                fileInfo.parent_guid = fileInfo.guid;
            }
            else
            {
                fileInfo.guid = Guid.NewGuid().ToString();
                fileInfo.parent_guid = parentGuid;
            }
            fileInfo.name = name;
            fileInfo.system_name = name;
            fileInfo.path = dirParentPath;
            fileInfo.size = 0;
            // fileInfo.extension = Path.GetExtension(file.FileName);
            fileInfo.create_time = DateTime.Now;
            fileInfo.update_time = DateTime.Now;
            fileInfo.parent_id = 0;
            fileInfo.type = "dir";
            fileInfo.user_id = base.LoginUserInfo.user_id;
            fileInfo.user_guid = base.LoginUserInfo.user_guid;
            fileInfo.from = "api";
            fileInfo.status = 0;
            fileInfo.space_type = spaceType;
            fileInfo.code = new UtilsOrderID().getCode1();
            new ServiceFile().add(fileInfo, parentGuid);
            return RespResult.Sucess("文件上传成功");
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public RespResultData delFile([FromForm] string guid)
        {
            string _fileServerDir = "";
            f_file file = new ServiceFile().getFileModel(guid);
            if (file.space_type == 0)
            {
                //个人空间
                _fileServerDir = _personfileServerDir + "/" + base.LoginUserInfo.user_guid;
            }
            else if (file.space_type == 1)
            {
                //公共空间
                _fileServerDir = _publicfileServerDir;
            }
            string dirPath = _CurrentDirectory + _fileServerDir + "/";
            new ServiceFile().updateDel(dirPath, guid);
            return RespResult.Sucess();
        }
        /// <summary>
        /// 获取文件下载地址
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public RespResultData getFileUrl([FromForm] string guid)
        {

            string host = HttpContext.Request.Host.ToString();
            string url = "";
            f_file file = new ServiceFile().getFileModel(guid);
            if (file.space_type == 0)
            {
                url = "http://" + host + "/PersonFileRoot" + "/" + base.LoginUserInfo.user_guid + "/" + file.path + "/" + file.name;
            }
            else if (file.space_type == 1)
            {
                url = "http://" + host + "/PublicFileRoot" + "/" + file.path + "/" + file.name;
            }
            return RespResult.Sucess(url);
        }
        /// <summary>
        /// 获取文件下载地址
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public async Task<IActionResult> getDownloadUrl(string guid)
        {
            //http://localhost:8060/api/file/getDownloadUrl?guid=9d6732ca-43f4-4a50-b866-2ed5c5e7843e
            string host = HttpContext.Request.Host.ToString();
            string fileurl = "";
            string dirPath = "";
            f_file file = new ServiceFile().getFileModel(guid);
            if (file.space_type == 0)
            {
                fileurl = "http://" + host + "/PersonFileRoot" + "/" + base.LoginUserInfo.user_guid + "/" + file.path + "/" + file.name;
                dirPath = _CurrentDirectory + "/" + _personfileServerDir + "/" + base.LoginUserInfo.user_guid + "/" + file.path + "/" + file.name;
            }
            else if (file.space_type == 1)
            {
                fileurl = "http://" + host + "/PublicFileRoot" + "/" + file.path + "/" + file.name;
                dirPath =_CurrentDirectory + "/" + _publicfileServerDir + "/" + file.path + "/" + file.name;
            }

            //写入数据库
           


            //如果是下载文件夹，则返回压缩包
            if (file.type == "dir")
            {
                string zipPath = dirPath + ".zip"; // 修改为在文件夹路径后直接添加 .zip

                // 确保路径中的双斜杠被替换为单斜杠
                zipPath = zipPath.Replace("//", "/");

                // 根据操作系统调整路径分隔符
                if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
                {
                    zipPath = zipPath.Replace("/", "\\");
                }

                // 检查ZIP文件是否存在，如果不存在则创建
                if (!System.IO.File.Exists(zipPath))
                {
                    ZipFile.CreateFromDirectory(dirPath, zipPath);
                }




                //这里需要记录压缩包地址，后期定时任务删除吧

                string parentGuid = file.parent_guid;
                string name = file.name + ".zip";
                string dirParentPath = file.path;
                int spaceType = (int)file.space_type;
                // 获取文件大小
                long fileSize = new FileInfo(zipPath).Length;

                f_file fileInfo = new f_file();
                if (string.IsNullOrEmpty(parentGuid))
                {
                    fileInfo.guid = Guid.NewGuid().ToString();
                    fileInfo.parent_guid = fileInfo.guid;
                }
                else
                {
                    fileInfo.guid = Guid.NewGuid().ToString();
                    fileInfo.parent_guid = parentGuid;
                }
                fileInfo.name = name;
                fileInfo.system_name = name;
                fileInfo.path = dirParentPath;
                fileInfo.size = fileSize;
                fileInfo.extension = Path.GetExtension(name);
                fileInfo.create_time = DateTime.Now;
                fileInfo.update_time = DateTime.Now;
                fileInfo.parent_id = 0;
                fileInfo.type = "file";
                fileInfo.user_id = base.LoginUserInfo.user_id;
                fileInfo.user_guid = base.LoginUserInfo.user_guid;
                fileInfo.from = "api";
                fileInfo.status = 2;
                fileInfo.space_type = spaceType;
                fileInfo.code = new UtilsOrderID().getCode1();
                new ServiceFile().add(fileInfo, parentGuid);



                // 返回ZIP文件              
                return File(System.IO.File.OpenRead(zipPath), "application/zip", file.name + ".zip");
            }
            else
            {
                // 下载文件
                using (var httpClient = new HttpClient())
                {
                    using (var response = await httpClient.GetAsync(fileurl, HttpCompletionOption.ResponseHeadersRead))
                    {
                        response.EnsureSuccessStatusCode();
                        var contentLength = response.Content.Headers.ContentLength;
                        using (var streamToReadFrom = await response.Content.ReadAsStreamAsync())
                        {
                            var inMemory = new MemoryStream();
                            await streamToReadFrom.CopyToAsync(inMemory);
                            inMemory.Seek(0, SeekOrigin.Begin);
                            return File(inMemory, response.Content.Headers.ContentType?.ToString(), file.name);
                        }
                    }
                }
            }
            // return RespResult.Sucess(url);
        }



    }
}
